Python uses indentation (spaces/tabs) to define code blocks. Every if, for, while, def, etc., must end with a colon and the body must be indented.
Each snippet below has one or more syntax errors. Type them into your IDE and fix them so they run correctly.
Problem 1: (Expected output: B)
score = 85
if score >= 90
print("A")
elif score >= 80:
print("B")
else:
print("C or below")
Problem 2: (Expected output: 0, 2, 4, 6, 8)
for i in range(5):
print(i * 2)
Problem 3: (Expected output: Hello, Alex)
greet = input('would you like to greet? (Y/N)')
if greet == 'Y':
print ('Hello, Alex')
| Cast | What it does | Common trap |
|---|---|---|
int(x) | Converts to integer (truncates) | int("3.5") โ ValueError |
float(x) | Converts to float | float("hello") โ ValueError |
str(x) | Converts to string | "3" + 3 โ TypeError |
Total: 21.8.price = input("Enter price: ")
tax = price * 0.09
total = price + tax
print("Total:", total)
print(int(9.9))
print(float("42"))
print(str(100) + " dollars")
print(int(float("7.5")))
Rules: Prefix the string with f. Variables go inside {}. Format specs: {value:.2f} for 2 decimals.
length = 7.5
width = 3.2
area = length * width
# Old style:
print("Length: " + str(length) + ", Width: " + str(width) + ", Area: " + str(area))
3x Coffee = $14.25item = "Coffee"
price = 4.75
qty = 3
# TODO: print the receipt
Compound logic requires the and, or, and not operators. To check if a number is even, use the modulo operator: number % 2 == 0.
if/elif/else to print exactly one of the following classifications:
Key questions for any loop: What is the starting condition? When does it stop? What updates the loop variable?
x = 10
while x > 0:
print(x)
x -= 3
while loop that runs exactly 3 times. Each time it loops, ask the user to input a float. Add that input to a total variable. After the loop finishes, print the average of the 3 numbers using an f-string rounded to 2 decimal places.total = 0.0
count = 0
# TODO: Write your while loop here
Let's combine everything: casting, branching, formatting, and looping.
secret_number variable to 42.while loop to keep asking the user for a guess until they get it right."Correct! You got it in X attempts!" (using an f-string).